package com.demo.demoproject.utils;

import com.demo.demoproject.constants.MailConstants;
import com.demo.demoproject.domain.Result;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;

import static com.demo.demoproject.constants.MailConstants.MAIL_SEND_FROM;

@Slf4j
@Component
@RequiredArgsConstructor
public class MailClient {
    private final JavaMailSender javaMailSender;
    private final StringRedisTemplate redisTemplate;
    private static final CustomString CAPTCHA = new CustomString().addString("captcha");

    /**
     * 生成邮件内容
     * @param text 要替换的邮件内容
     * @param template 邮件模板
     * @return 邮件内容
     */
    @NotNull
    private static String buildMailContent(String text, String template) {
        ClassPathResource resource = new ClassPathResource(template);
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new java.io.InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            log.info("failed to load template file");
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    log.info("failed to close file reader");
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.info("failed to close input stream");
                }
            }
        }

        // 替换模板中的参数
        return MessageFormat.format(buffer.toString(), text);
    }

    /**
     * 发送验证码
     * @param to 收件人
     * @param subject 主题
     * @param template 模板
     * @return 发送结果
     * @throws MessagingException 发送失败
     */
    public Result sendCaptcha(String to, String subject, String template) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();

        try {
            String captcha = CaptchaGenerator.getRandomCaptcha(MailConstants.DEFAULT_LENGTH_CAPTCHA);
            // 存入 Redis缓存
            String path = CAPTCHA.addStringWithColon(to).transferToString();
            redisTemplate.opsForValue().set(path, captcha);
            String content = buildMailContent(captcha, template);

            // 邮件内容
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setSubject(subject);
            helper.setText(content);
            helper.setTo(to);
            helper.setFrom(MAIL_SEND_FROM);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.info("failed to send mail");
            return Result.fail(500, "FAILED_SEND_MAIL");
        }
        return Result.success();
    }
}
